package com.rong.template.service;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rong.template.advice.filter.PageLimit;
import com.rong.template.advice.filter.PageLimitHolderFilter;
import com.rong.template.bean.bo.UserMessage;
import com.rong.template.cache.RedisKeyConstant;
import com.rong.template.cache.RedisClient;
import com.rong.template.constant.UITypeEnum;
import com.rong.template.mapper.UserMessagePoMapper;
import com.rong.template.mapper.pojo.UserMessagePo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 系统配置服务
 * 
 * @author rongyi
 */
@Slf4j
@Service
public class UserMessageService {

	@Autowired
	private UserMessagePoMapper userMessagePoMapper;

	@Autowired
	private RedisClient redisClient;


	public  List<UserMessage> selectMsgInfo(String userId) throws Exception{

		//userId不为空时，优先查询缓存
		if(StrUtil.isNotEmpty(userId)){
			String key = RedisKeyConstant.CACHE_TYPE_USER+RedisKeyConstant.UNDERLINE+userId;

			UserMessage userMessage= redisClient.getObject(key,UserMessage.class);
			if(userMessage != null){
				log.info("查询redis: userMessage="+userMessage);
				List<UserMessage> list= new ArrayList<>();
				list.add(userMessage);
				return list;
			}
		}


		UserMessagePo reqPo=new UserMessagePo();
		reqPo.setAccountId(userId);
		List<UserMessagePo> polist=userMessagePoMapper.selectMsgInfo( reqPo);

		if(CollUtil.isEmpty(polist)){
			log.info("用户消息不存在，userId="+userId);
			return null;
		}

		//存储redis
		if(StrUtil.isNotEmpty(userId)){
			String key = RedisKeyConstant.CACHE_TYPE_USER+RedisKeyConstant.UNDERLINE+userId;
			UserMessage userMessage=new UserMessage();
			BeanUtil.copyProperties(polist.get(0),userMessage);
			log.info("存储redis: userMessage="+userMessage);
			redisClient.setObject(key,userMessage,10, TimeUnit.SECONDS);
		}

		//封装转换
		List<UserMessage> msgList=polist.stream().map(x -> {
			UserMessage userMessage=new UserMessage();
			BeanUtil.copyProperties(x,userMessage);

			//获取枚举值描述
			userMessage.setUiTypeDesc(UITypeEnum.getNameByOpenType(userMessage.getUiType()));
			return userMessage;
		}).collect(Collectors.toList());

		//分页查询: totalCount
		if(PageLimitHolderFilter.getContext() != null){
			PageLimitHolderFilter.getContext().setTotalCount(userMessagePoMapper.selectTotalCount(reqPo));
		}

		return msgList;
	}

	public  List<UserMessage> selectPageByUserId(String userId) throws Exception{
		log.info("查个小分页，userId="+userId);
		UserMessagePo reqPo=new UserMessagePo();
		reqPo.setAccountId(userId);

		PageLimit pageLimit = PageLimitHolderFilter.getContext();
		List<UserMessagePo> polist;

		if(pageLimit.isToPage()){
			//开启分页：会默认查询总数
			PageHelper.startPage(pageLimit.getPageNum(),pageLimit.getPageSize());

			//紧跟着的第一个select方法才会被分页
			polist = userMessagePoMapper.selectMsgInfo( reqPo);

			//分页后，实际返回的结果list类型是Page<E>（ArrayList子类），如果想取出分页信息，需要强制转换为Page<E>，
			Page<UserMessagePo> pages = (Page<UserMessagePo>)polist;
			//记录到线程上下文
			pageLimit.setTotalCount(pages.getTotal());

		}else {

			//这时候返回的就是真正的list,要是再强制转换的话就要报类型转换错误了
			polist = userMessagePoMapper.selectMsgInfo( reqPo);
		}


		if(CollUtil.isEmpty(polist)){
			log.info("用户消息不存在，userId="+userId);
			return null;
		}

		//封装转换
		List<UserMessage> msgList=polist.stream().map(x -> {
			UserMessage userMessage=new UserMessage();
			BeanUtil.copyProperties(x,userMessage);
			return userMessage;
		}).collect(Collectors.toList());

		return msgList;
	}

	public PageInfo pageInfoByUserId(String userId) throws Exception{

		UserMessagePo reqPo=new UserMessagePo();
		reqPo.setAccountId(userId);

		//开启分页
		PageLimit pageLimit = PageLimitHolderFilter.getContext();
		if(pageLimit.isToPage()){
			PageHelper.startPage(pageLimit.getPageNum(),pageLimit.getPageSize());
		}
		List<UserMessagePo> polist=userMessagePoMapper.selectMsgInfo( reqPo);

		//内部会将所有分页参数全部封装进去
		PageInfo pageInfo= new PageInfo(polist, pageLimit.getPageSize());

		return pageInfo;
	}
}
